package com.ruoyi.base.ch340;

import com.fazecast.jSerialComm.SerialPort;
import org.springframework.stereotype.Service;

@Service
public class Ch340Service {

    SerialPort serialPort;
    String result;

    public String sendAndRead(String s){

        // 获取所有可用串口
//        SerialPort[] ports = SerialPort.getCommPorts();
//        System.out.println("Available ports:");
//        for (SerialPort port : ports) {
//            System.out.println(port.getSystemPortName());
//        }

        // 打开串口
        serialPort = SerialPort.getCommPort(Ch340Configure.Port);
        serialPort.setBaudRate(Ch340Configure.BaudRate);
        serialPort.setNumDataBits(Ch340Configure.NumDataBits);
        serialPort.setNumStopBits(Ch340Configure.NumStopBits);
        serialPort.setParity(Ch340Configure.NO_PARITY);

        if (!serialPort.openPort()) {
            throw new RuntimeException("连接设备串口失败！");
        }

        // 设置读取超时
        serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);

        // 发送数据
        byte[] writeBuffer = s.getBytes();
        serialPort.writeBytes(writeBuffer, writeBuffer.length);
        System.out.println("Sent: " + s);


        // 读取数据
        try {
            for (int i = 0; i < 50; i++) {
                if (serialPort.bytesAvailable() == 0)
                    Thread.sleep(100);
                else break;
            }

            byte[] readBuffer = new byte[serialPort.bytesAvailable()];
            serialPort.readBytes(readBuffer, readBuffer.length);
            result = new String(readBuffer);
            result = result.replaceAll("\\s", "");
            System.out.println("Read: " + result);

            if (result.length() == 0){
                throw new RuntimeException("设备回复数据超时！");
            }

        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(),e);
        } finally {
            serialPort.closePort();
        }
        return result;
    }


}
